package com.vichat.api.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sun.org.apache.xpath.internal.operations.Or;
import com.vichat.api.exception.VCException;
import com.vichat.api.vo.*;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class VichatHttpSDK {
    private static Log logger = LogFactory.getLog(VichatHttpSDK.class);
    public static String POST_URL = "http://47.104.186.84/api/post";
    public static String APP_ID = null;
    public static String PARTY_KEY = null;
    public static long PARTY_ID = -1;
    public static String APP_TYPE = "C";


    public static void init(String url, String partyKey, long partyId) {
        POST_URL = url;
        APP_ID = String.valueOf(partyId);
        PARTY_ID = partyId;
        PARTY_KEY = partyKey;
    }

    public static Company registerCompany(Company company) throws VCException {
        String key = "company";
        String method = "vc.register_company";

        JSONObject responseContent = post(key, method, company);

        Company rtnCompany = JSONObject.parseObject(responseContent.getString(key), Company.class);
        return rtnCompany;
    }

    /**
     * 添加用户
     *
     * @return
     */
    public static List<User> addUser(List<User> users) throws VCException {
        String key = "user";
        String method = "vc.add_user";

        JSONObject responseContent = post(key, method, users);

        List<User> rtnUsers = JSONArray.parseArray(responseContent.getString(key), User.class);
        return rtnUsers;
    }

    /**
     * 修改用户信息
     *
     * @param users
     * @return
     */
    public static List<User> modeUser(List<User> users) throws VCException {

        String key = "user";
        String method = "vc.mod_user";

        JSONObject responseContent = post(key, method, users);

        List<User> rtnUsers = JSONArray.parseArray(responseContent.getString(key), User.class);
        return rtnUsers;
    }

    /**
     * 删除用户
     *
     * @param users
     * @return
     */
    public static List<User> delUser(List<User> users) throws VCException {
        String key = "user";
        String method = "vc.del_user";

        JSONObject responseContent = post(key, method, users);

        List<User> rtnUsers = JSONArray.parseArray(responseContent.getString(key), User.class);
        return rtnUsers;
    }


    /**
     * 重置密码
     *
     * @param users
     * @return
     */
    public static List<User> resetPasswd(List<User> users) throws VCException {
        String key = "user";
        String method = "vc.reset_passwd";

        JSONObject responseContent = post(key, method, users);

        List<User> rtnUsers = JSONArray.parseArray(responseContent.getString(key), User.class);
        return rtnUsers;
    }

    /**
     * 用户激活(延期)
     *
     * @param users
     * @return
     */
    public static List<User> acitivityUser(List<User> users) throws VCException {
        String key = "user";
        String method = "vc.activity_user";

        JSONObject responseContent = post(key, method, users);

        List<User> rtnUsers = JSONArray.parseArray(responseContent.getString(key), User.class);
        return rtnUsers;
    }

    /**
     * 添加频道
     *
     * @param room
     * @return
     */
    public static Room addRoom(Room room) throws VCException {
        String key = "room";
        String method = "vc.add_room";

        JSONObject responseContent = post(key, method, room);

        Room rtnRoom = JSONObject.parseObject(responseContent.getString(key), Room.class);
        return rtnRoom;
    }

    /**
     * 修改频道信息
     *
     * @param room
     * @return
     */
    public static Room modRoom(Room room) throws VCException {
        String key = "room";
        String method = "vc.mod_room";

        JSONObject responseContent = post(key, method, room);

        Room rtnRoom = JSONObject.parseObject(responseContent.getString(key), Room.class);
        return rtnRoom;
    }

    /**
     * 删除频道
     *
     * @param room
     * @return
     */
    public static Room delRoom(Room room) throws VCException {
        String key = "room";
        String method = "vc.del_room";

        JSONObject responseContent = post(key, method, room);

        Room rtnRoom = JSONObject.parseObject(responseContent.getString(key), Room.class);
        return rtnRoom;
    }

    /**
     * 添加频道用户
     *
     * @param roomUser
     * @return
     */
    public static RoomUser addRoomUser(RoomUser roomUser) throws VCException {
        String key = "roomUser";
        String method = "vc.add_roomuser";

        JSONObject responseContent = post(key, method, roomUser);

        RoomUser rtnRoomUser = JSONObject.parseObject(responseContent.getString(key), RoomUser.class);
        return rtnRoomUser;
    }

    /**
     * 删除频道用户
     *
     * @param roomUser
     * @return
     */
    public static RoomUser delRoomUser(RoomUser roomUser) throws VCException {
        String key = "roomUser";
        String method = "vc.del_roomuser";

        JSONObject responseContent = post(key, method, roomUser);

        RoomUser rtnRoomUser = JSONObject.parseObject(responseContent.getString(key), RoomUser.class);
        return rtnRoomUser;
    }

    /**
     * 获取用户轨迹信息
     *
     * @param locationDataVO
     * @return
     */
    public static LocationDataVO getLocationLog(LocationDataVO locationDataVO) throws VCException {
        String key = "locationData";
        String method = "vc.get_locationlog";

        JSONObject responseContent = post(key, method, locationDataVO);

        LocationDataVO rtnLocationData = JSONObject.parseObject(responseContent.getString(key), LocationDataVO.class);
        return rtnLocationData;
    }

    /**
     * 获取企业在线用户定位信息
     *
     * @param company
     * @return
     */
    public static List<LocationDataVO> getOnlineLocation(Company company) throws VCException {
        String key = "company";
        String method = "vc.get_locationlog";

        JSONObject responseContent = post(key, method, company);

        List<LocationDataVO> rtnLocationDatas = JSONArray.parseArray(responseContent.getString("locationData"), LocationDataVO.class);
        return rtnLocationDatas;
    }

    /**
     * 获取指定用户定位信息
     *
     * @param locationDataVO
     * @return
     */
    public static List<LocationDataVO> getSelectLocation(LocationDataVO locationDataVO) throws VCException {
        String key = "user";
        String method = "vc.get_selectuserlocation";

        JSONObject responseContent = post(key, method, locationDataVO);

        List<LocationDataVO> rtnLocationDatas = JSONArray.parseArray(responseContent.getString("locationData"), LocationDataVO.class);
        return rtnLocationDatas;
    }

    /**
     * 设置用户定位开关
     *
     * @param locationDataVO
     * @return
     */
    public static void locationSwitch(LocationDataVO locationDataVO) throws VCException {
        String key = "user";
        String method = "vc.get_selectuserlocation";

        JSONObject responseContent = post(key, method, locationDataVO);
    }

    /**
     * 创建临时频道
     *
     * @param room
     * @return
     */
    public static Room createPersonalChannel(Room room) throws VCException {
        String key = "room";
        String method = "vc.create_personal_room";

        JSONObject responseContent = post(key, method, room);

        Room rtnRoom = JSONObject.parseObject(responseContent.getString(key), Room.class);
        return rtnRoom;
    }

    /**
     * 添加企业
     *
     * @param org
     * @return
     */
    public static Org addOrg(Org org) throws VCException  {
        String key = "org";
        String method = "vc.add_org";

        JSONObject responseContent = post(key, method, org);

        Org rtnOrg = JSONObject.parseObject(responseContent.getString(key), Org.class);
        return rtnOrg;
    }

    /**
     * 修改企业信息
     *
     * @param org
     * @return
     */
    public static Org modOrg(Org org) throws VCException  {
        String key = "org";
        String method = "vc.mod_org";

        JSONObject responseContent = post(key, method, org);

        Org rtnOrg = JSONObject.parseObject(responseContent.getString(key), Org.class);
        return rtnOrg;
    }

    /**
     * 修改企业信息
     *
     * @param org
     * @return
     */
    public static Org delOrg(Org org) throws VCException  {
        String key = "org";
        String method = "vc.del_org";

        JSONObject responseContent = post(key, method, org);

        Org rtnOrg = JSONObject.parseObject(responseContent.getString(key), Org.class);
        return rtnOrg;
    }

    public static JSONObject post(String key, String method, Object obj) throws VCException {

        JSONObject contentJson = new JSONObject();
        RequestBusiRecord requestBusiRecord = getRequestBusiRecord();

        contentJson.put(key, obj);

        requestBusiRecord.setRequestContent(contentJson.toJSONString());
        requestBusiRecord.setMethod(method);

        String respJson = JSON.toJSONString(requestBusiRecord);
        String response = doPost(POST_URL, respJson);
        ResponseBusiRecord responseBusiRecord = JSONObject.parseObject(response, ResponseBusiRecord.class);
        if (!"0000".equals(responseBusiRecord.getResponseCode())) {
            throw new VCException(responseBusiRecord.getResponseCode(), responseBusiRecord.getResponseMsg());
        }
        JSONObject responseContent = JSONObject.parseObject(responseBusiRecord.getResponseContent());
        return responseContent;

    }

    public static RequestBusiRecord getRequestBusiRecord() {
        RequestBusiRecord requestBusiRecord = new RequestBusiRecord();

        requestBusiRecord = new RequestBusiRecord();
        requestBusiRecord.setAppId(APP_ID);
        requestBusiRecord.setAppType(APP_TYPE);
        String timestamp = String.valueOf(new Date().getTime());
        requestBusiRecord.setTimestamp(timestamp);
        String sign = Md5Util.Md5Encode(PARTY_KEY + timestamp, null);
        requestBusiRecord.setSign(sign);
        return requestBusiRecord;

    }

    /**
     * post 方法
     *
     * @param url
     * @param json
     * @return
     */
    private static String doPost(String url, String json) {
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost method = new HttpPost(url);
        String responseBody = null;
        try {
            method.addHeader("Content-type", "application/json; charset=utf-8");
            method.setHeader("Accept", "application/json");
            method.setEntity(new StringEntity(json, Charset.forName("UTF-8")));
            //long startTime = System.currentTimeMillis();
            HttpResponse response = httpClient.execute(method);
            //long endTime = System.currentTimeMillis();
            int statusCode = response.getStatusLine().getStatusCode();
            //System.out.println("statusCode:" + statusCode);
            //System.out.println("调用API 花费时间(单位：毫秒)：" + (endTime - startTime));
            if (statusCode != HttpStatus.SC_OK) {
                logger.error("Method failed:" + response.getStatusLine());
            }
            System.out.println(json);
            responseBody = EntityUtils.toString(response.getEntity());
            //System.out.println("输出参数：" + responseBody);
        } catch (IOException e) {
            // 网络错误
            e.printStackTrace();
        } finally {
            return responseBody;
        }
    }

}
